;;ErlangHelper main file.
;;License New BSD
;;2009 Sunny, SDNU.
;any questions, contact <catsunny@gmail.com>


(defun doprompt()
  (interactive)
  (let (CurrentPoint,fun,tag,module,tmp,tmp1)
    (setq CurrentPoint (point))
    (backward-char)
    (setq fun (thing-at-point 'word)) ;get current fun name
    (backward-word)  
    (setq tmp (point))
    (backward-char)
    (setq tmp1 (point))
    (setq tag (buffer-substring tmp1 tmp));try to get ":"
    (if (equal tag ":") 
	(progn ;;has ":", go on getting the module name
	  (backward-word)
	  (setq module (thing-at-point 'word)))
      (setq module "erlang")) ;;no ":", maybe erlang BIF, using erlang as module name.
    ;;(setq fullname (concat module ":" fun))
    (goto-char CurrentPoint)
    (insert "(")
    
    ;Get Prompt
    (catch 'done
      (el_search module fun))
    ;Display Prompt
    (message result)))

;search for module
(defun el_search(module fun)
  (let(name,sublist,name2,n,nn)
    (setq n 0)
    (while (> 1 0)
      (setq name (nth n el_module_prompts))
      (when (equal name nil) 
	(setq result (concat module ": Prompt for the module not found."))
	(throw 'done t))
      (when (equal name module) ;;found module name. go on searching for fun name
	(setq sublist (nth (+ 1 n) el_module_prompts)) ;get sublist for this module
	(setq nn 0)
	(while(> 1 0)
	  (setq name2 (nth nn sublist))
	  (when (equal name2 nil)
	    (setq result (concat fun ": Prompt for the fun not found."))
	    (throw 'done t))
	  (when (equal name2 fun)
	    (setq result (nth (+ 1 nn) sublist))
	    (throw 'done t))
	  (setq nn (+ 2 nn))))
      (setq n (+ 2 n)))))

;helper functions 
(defun el_add(list key value)
  (cons key (cons value list)))
   

;for modules
(setq entry_count 0)
(defun entry(phrase prompt)
  (progn
    (setq tmp (el_add tmp phrase prompt))
    (setq entry_count (+ 1 entry_count))))

;for main
(defun load_and_save(modulename filename)
  (let (PreviousCount,CurrentCount)
    (setq PreviousCount entry_count)
    (load-file filename)
    (message "\tloaded %d function prompts for module %s from file %s" (- entry_count PreviousCount) modulename filename)
    (setq el_module_prompts (el_add el_module_prompts modulename tmp))))
    


;start here!
(setq el_module_prompts '()) ;format: name0 list0 name1 list1...
(setq tmp '())
(load_and_save "lists" "el_lists.el")

;ready to go
(global-set-key "(" 'doprompt)

;ask if people may help the authors
(message "ErlangHelper is open source software, please consider a little donation (5$ or 10$) if you find ErlangHelper useful and wants to help make it better! ")

